Reverse words in a string¶
Time: O(N); Space: O(N); medium
Given an input string, reverse the string word by word.
Example 1:
Input: s = “the sky is blue”
Output: “blue is sky the”
Example 2:
Input: s = ” hello world! “
Output: “world! hello”
Explanation:
Your reversed string should not contain leading or trailing spaces.
Example 3:
Input: s = “a good example”
Output: “example good a”
Explanation:
You need to reduce multiple spaces between two words to a single space in the reversed string.
Clarification 1. What constitutes a word? A sequence of non-space characters constitutes a word. 2. Could the input string contain leading or trailing spaces? Yes. However, your reversed string should not contain leading or trailing spaces. 3. How about multiple spaces between two words? Reduce them to a single space in the reversed string.
[1]:
class Solution1(object):
def reverseWords(self, s):
"""
:type string: s
:rtype: string
"""
return ' '.join(reversed(s.split()))
[2]:
sol = Solution1()
s = "the sky is blue"
assert sol.reverseWords(s) == "blue is sky the"
s = " hello world! "
assert sol.reverseWords(s) == "world! hello"
s = "a good example"
assert sol.reverseWords(s) == "example good a"